//
//  StarLeavewordViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2017/5/18.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "StarLeavewordViewController.h"
#import "ChatKeyBoard.h"
#import "SuperCommentCell.h"
#import "SuperCommentModel.h"

@interface StarLeavewordViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,SuperCommentCellDelegate>{
    NSMutableArray *_leavelistArray;
    UITextField *_msgInputFeild;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *msgInputView;
@property (nonatomic, assign) CGFloat history_Y_offset;//记录table的offset.y
@property (nonatomic, assign) CGFloat seletedCellHeight;//记录点击cell的高度，高度由代理传过来
@property (nonatomic, assign) BOOL isShowKeyBoard;//记录点击cell的高度，高度由代理传过来
@property (nonatomic, assign) BOOL needUpdateOffset;//控制是否刷新table的offset
@property (nonatomic,copy)NSIndexPath *currentIndexPath;
@property (nonatomic, strong) CommentModel *replayTheSeletedCellModel;//专门用来回复选中的cell的model
@property (nonatomic, copy) NSString *parentId;
@property (nonatomic, copy) NSString *parentudid;
@property (nonatomic, copy) NSString *replyname;
@end

@implementation StarLeavewordViewController

- (UIView *)msgInputView {
    if (!_msgInputView) {
        //输入框
        _msgInputView = [[UIView alloc] initWithFrame:CGRectMake(0, kSCREEN_HEIGHT -kNAV_HEIGHT, kSCREEN_WIDTH, 50 )];
        _msgInputView.backgroundColor = [UIColor whiteColor];
        UIView *sepline = [[UIView alloc] init];
        [_msgInputView addSubview:sepline];
        sepline.frame = CGRectMake(0, 0, kSCREEN_WIDTH, 0.5);
        sepline.backgroundColor = [UIColor cellLineColor];
        UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        sendBtn.frame = CGRectMake(self.view.width - 15 - 50, 0, 50, 50);
        [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        [sendBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [sendBtn setTitleColor:UIColorFromRGB(0x0ACCAC) forState:UIControlStateNormal];
        [sendBtn setBackgroundColor:[UIColor clearColor]];
        [sendBtn addTarget:self action:@selector(clickSend:) forControlEvents:UIControlEventTouchUpInside];
        
        _msgInputFeild = [[UITextField alloc] initWithFrame:CGRectMake(10,7.5,sendBtn.left - 20,30)];
        _msgInputFeild.backgroundColor = [UIColor clearColor];
        _msgInputFeild.returnKeyType = UIReturnKeySend;
        _msgInputFeild.borderStyle = UITextBorderStyleRoundedRect;
        _msgInputFeild.placeholder = @"留下你想对明星说的话...";
        _msgInputFeild.delegate = self;
        _msgInputFeild.textColor = [UIColor blackColor];
        _msgInputFeild.font = [UIFont systemFontOfSize:14];
        
        [_msgInputView addSubview:_msgInputFeild];
        [_msgInputView addSubview:sendBtn];
        
    }
    return _msgInputView;
}

//监听键盘高度变化
-(void)keyboardFrameDidChange:(NSNotification*)notice
{
    NSDictionary * userInfo = notice.userInfo;
    NSValue * endFrameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect endFrame = endFrameValue.CGRectValue;
    [UIView animateWithDuration:0.25 animations:^{
        _msgInputView.y = endFrame.origin.y - _msgInputView.height - kNAV_HEIGHT;
        if (_msgInputView.y == kSCREEN_HEIGHT-kNAV_HEIGHT-50) {
            self.parentId = @"";
            self.parentudid = @"";
            _msgInputFeild.placeholder = @"留下你想对明星说的话...";
        }
    }];
}

#pragma mark -- 留言列表
- (void)LeaveListRequest {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"cid":User_ID,
                           @"type":@"30", //留言列表
                           @"page":@"1"
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:KSCommentList];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            NSArray *array = responseObject[@"data"][@"list"];
            for (NSDictionary *commentDict in array) {
                SuperCommentModel *model1 = [[SuperCommentModel alloc] initWithDict:commentDict];
                NSArray *commentArr = model1.children;
                model1.commentArray = [NSMutableArray arrayWithCapacity:1];
                for (NSDictionary *cidict in commentArr) {
                    CommentModel *model = [[CommentModel alloc] initWithDict:cidict];
                    [model1.commentArray addObject:model];
                }
                [_leavelistArray addObject:model1];
            }
            [self.tableView reloadData];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

#pragma mark -- 留言回复request
//发送留言 type:@"30"
- (void)SendLeaveWordRequestWithContent:(NSString *)content Parent:(NSString *)parent Pudid:(NSString *)pudid {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
//                           @"cid":self.s_uid,
                           @"description":content,
                           @"type":@"30",
                           @"parent":parent,
                           @"pudid":pudid
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kSendComment];
    [self showHUDInView:self.view title:nil];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [_msgInputFeild resignFirstResponder];
        [self hideHUD];
        if ([responseObject[@"code"] intValue] == 200) {
            _msgInputFeild.text = nil;
            _msgInputFeild.placeholder = @"留下你想对明星说的话...";
            [self showTitle:responseObject[@"data"][@"message"]];
            NSDictionary *newData = responseObject[@"data"][@"comment"];
            [self updateReplylistWithData:newData];
        }
    } failureBlock:^(NSError *error) {
        [_msgInputFeild resignFirstResponder];
        [self hideHUD];
    } showHUD:NO];
}
//更新留言子回复列表
- (void)updateReplylistWithData:(NSDictionary *)dataDict {
    CommentModel *model = [[CommentModel alloc] init];
    model.c_udid = dataDict[@"c_uid"];
//    model.cid = self.s_uid;
    model.c_content = dataDict[@"c_content"];
    model.c_createtime = dataDict[@"c_createtime"];
    model.cnickname = dataDict[@"u_nickname"];
    model.pnickname = self.replyname;
    model.c_parent = dataDict[@"c_parent"];
    model.c_parudid = dataDict[@"c_parudid"];
    SuperCommentModel *superModel = [_leavelistArray objectAtIndex:self.currentIndexPath.row];
    superModel.shouldUpdateCache = YES;
    [superModel.commentArray addObject:model];
    superModel.shouldUpdateCache = YES;
    [self reloadCellHeightForModel:superModel atIndexPath:self.currentIndexPath];
}

- (void)reloadCellHeightForModel:(SuperCommentModel *)model atIndexPath:(NSIndexPath *)indexPath{
    model.shouldUpdateCache = YES;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameDidChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [self setUpUI];
}
- (void)setNav {
}

#pragma mark -- UI
- (void)setUpUI {
    _leavelistArray = [NSMutableArray arrayWithCapacity:1];
    //tableView
    [self creatTableView];
    
}
- (void)creatTableView {
    self.tableView = [[UITableView alloc] init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView registerClass:[SuperCommentCell class] forCellReuseIdentifier:@"superCommentCellID"];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}

#pragma mark -- tableView 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _leavelistArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SuperCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"superCommentCellID"];
    cell.delegate = self;
    __weak __typeof(self) weakSelf= self;
    __block SuperCommentModel *model = [_leavelistArray objectAtIndex:indexPath.row];
    [cell configCellWithModel:model indexPath:indexPath];
    //点击文字
    cell.TapTextBlock=^(UILabel *desLabel){
        if (self.isShowKeyBoard) {
            [self.view endEditing:YES];
            return ;
        }
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:desLabel.text delegate:weakSelf cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    };
    cell.TapReplyBlock =  cell.TapReplyBlock = ^(UIButton *replyBtn){
        [_msgInputFeild becomeFirstResponder];
        _msgInputFeild.placeholder = [NSString stringWithFormat:@"回复:@%@",model.u_nickname];
        self.replyname = model.u_nickname;
        weakSelf.parentId = model.cid;
        weakSelf.parentudid = model.c_udid;
        weakSelf.currentIndexPath = indexPath;
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SuperCommentModel *model = _leavelistArray[indexPath.row];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SuperCommentModel *model = [_leavelistArray objectAtIndex:indexPath.row];
    CGFloat h = [SuperCommentCell hyb_heightForTableView:tableView config:^(UITableViewCell *sourceCell) {
        SuperCommentCell *cell = (SuperCommentCell *)sourceCell;
        [cell configCellWithModel:model indexPath:indexPath];
    } cache:^NSDictionary *{
        NSDictionary *cache = @{kHYBCacheUniqueKey : model.cid,
                                kHYBCacheStateKey  : @"",
                                kHYBRecalculateForStateKey : @(model.shouldUpdateCache)};
        model.shouldUpdateCache = NO;
        return cache;
    }];
    return h;
}

#pragma mark -- 发送留言
- (void)clickSend:(UIButton *)sender {
    if (_msgInputFeild.text.length) {
        [self SendLeaveWordRequestWithContent:_msgInputFeild.text Parent:self.parentId Pudid:self.parentudid];
    } else {
        [self showTitle:@"请您输入留言内容"];
    }
}
#pragma mark -- SuperCommentCellDelegate
-  (void)passCellHeight:(CGFloat )cellHeight commentModel:(CommentModel *)commentModel   commentCell:(CommentCell *)commentCell SuperCommentCell:(SuperCommentCell *)superCommentCell {
    self.replyname = commentModel.cnickname;
    self.needUpdateOffset = YES;
    self.replayTheSeletedCellModel = commentModel;
    self.currentIndexPath = [self.tableView indexPathForCell:superCommentCell];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.history_Y_offset = [commentCell.contentLabel convertRect:commentCell.contentLabel.bounds toView:window].origin.y;
    self.seletedCellHeight = cellHeight;
}

#pragma mark -- UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (_msgInputFeild.text.length) {
        [self SendLeaveWordRequestWithContent:_msgInputFeild.text Parent:self.parentId Pudid:self.parentudid];
    } else {
        [self showTitle:@"请您输入留言内容"];
    }
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
